//
//  EnableSwipeBackGesture.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/4/5.
//
// 当隐藏导航栏时，系统滑动返回的手势也会消失，
// 自定义修饰器 解决滑动返回问题

import SwiftUI

struct SwipeGestureController: UIViewControllerRepresentable {
    let enable: Bool

    func makeUIViewController(context _: Context) -> UIViewController {
        GestureHandlerViewController(enable: enable)
    }

    func updateUIViewController(_ uiViewController: UIViewController, context _: Context) {
        if let handlerVC = uiViewController as? GestureHandlerViewController {
            handlerVC.enableSwipe = enable
        }
    }

    private class GestureHandlerViewController: UIViewController {
        var enableSwipe: Bool = true

        init(enable: Bool) {
            enableSwipe = enable
            super.init(nibName: nil, bundle: nil)
        }

        @available(*, unavailable)
        required init?(coder _: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)

            guard let nav = navigationController else { return }
            nav.interactivePopGestureRecognizer?.isEnabled = enableSwipe
            nav.interactivePopGestureRecognizer?.delegate = nil
        }
    }
}

struct EnableSwipeBackGesture: ViewModifier {
    let enable: Bool

    func body(content: Content) -> some View {
        content
            .background(SwipeGestureController(enable: enable).frame(width: 0, height: 0))
    }
}

extension View {
    func enableSwipeBackGesture(enable: Bool) -> some View {
        modifier(EnableSwipeBackGesture(enable: enable))
    }
}


// TODO 移出去
struct RefreshOnActiveModifier: ViewModifier {
    let action: () -> Void
    
    @Environment(\.scenePhase) var scenePhase
    
    func body(content: Content) -> some View {
        content
            .onChange(of: scenePhase) { newPhase in
                if newPhase == .active {
                    action()
                }
            }
    }
}

extension View {
    func onActiveRefresh(perform action: @escaping () -> Void) -> some View {
        self.modifier(RefreshOnActiveModifier(action: action))
    }
}
